#include <iostream>
#include <cstdio>
#include <pthread.h>
#include <unistd.h>

using namespace std;
#define NUM 5

int cnt = 0;

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

void *threadRoutine(void *args)
{
    pthread_detach(pthread_self());

    uint64_t i = (uint64_t)args;
    while(true)
    {
        sleep(1);
        pthread_mutex_lock(&lock);

        pthread_cond_wait(&cond, &lock); //申请锁的同时会释放锁

        cout << "thread-> " << i << " cnt: " << cnt++ << endl;

        pthread_mutex_unlock(&lock);
        usleep(1000);
    }

    pthread_exit((void*)666);
}

int main()
{
    pthread_t tid;
    for(int i = 0; i < NUM; i++)
    {
        pthread_create(&tid, nullptr, threadRoutine, (void*)i);
    }

    //主线程释放其他线程就会自动释放
    while(true)
    {
        // pthread_cond_signal(&cond); //唤醒该队列下首个线程
        //主线程唤醒在锁资源等待队列的线程
        sleep(1);
        pthread_cond_broadcast(&cond);

    }
    return 0;
}






// pthread_mutex_t lock;

// void *threadRoutine(void *args)
// {
//     pthread_mutex_lock(&lock);
//     pthread_mutex_lock(&lock);

//     pthread_exit((void*)6666);
// }

// int main()
// {
//     pthread_mutex_init(&lock, nullptr);
//     pthread_t tid;
//     pthread_create(&tid, nullptr, threadRoutine, nullptr);    

//     pthread_join(tid, nullptr);
//     pthread_mutex_destroy(&lock);

//     return 0;
// }

